package org.personal.listener;

import java.util.List;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.myhibernate.ProxyTemplate;
import org.myhibernate.Template;
import org.myhibernate.core.method.PageSizeQuery;
import org.personal.entity.Group;
import org.personal.entity.Page;
import org.personal.entity.User;
import org.personal.init.InitData;

import com.util.ConfigUtil;

public class SystemListener implements ServletContextListener
{

	public void contextDestroyed(ServletContextEvent sce) 
	{
	}

	public void contextInitialized(ServletContextEvent sce) 
	{
		Template<Group> template=new ProxyTemplate(Group.class).getInstance();
		Template<User> template_User=new ProxyTemplate(User.class).getInstance();
		try 
		{
			PageSizeQuery<Group> query=template.getPageSizeQuery();
			int count=query.query(" where name='admins' ");
			Group admins=null;
			if (count==0)
			{
				admins=new Group();
				admins.setName("admins");
				template.save(admins);
			}else 
			{
				admins=query.getListObject(0,count).get(0);
				//查询该组的子组
				count=query.query(" where groups like '%;"+admins.getId()+";%' ");
				List idList=query.getIdList();
				for (int i = 0; i < idList.size(); i++) 
				{
					admins.getChildren().add(idList.get(i)+"");
				}
				//查询该组的子用户
				PageSizeQuery<User> queryUser=template_User.getPageSizeQuery();
				count=queryUser.query(" where parents like '%;"+admins.getId()+";%' ");
				idList=queryUser.getIdList();
				for (int i = 0; i < idList.size(); i++) 
				{
					admins.getChildren().add(idList.get(i)+"");
				}
			}
			String adminString=ConfigUtil.getAttribute("admins");
			String[] ss=adminString.split(",");
			for (int i = 0; i < ss.length; i++) 
			{
				if (admins.getChildren().contains(ss[i])==false)
				{
					admins.getChildren().add(ss[i]);
				}
			}
			Group.setAdmins(admins);
			System.out.println("Listener inited admins.getChildren="+admins.getChildren());
		} catch (Exception e) 
		{
			e.printStackTrace();
		}finally
		{
			template.close();
			template_User.close();
		}
		/**
		 * 检查是否初始化了数据
		 */
		Template<Page> template_page=new ProxyTemplate(Page.class).getInstance();
		try 
		{
			if (!template_page.exist(1))
			{
				InitData initData=new InitData();
				initData.init();
			}
		} catch (Exception e) 
		{
			e.printStackTrace();
		}finally
		{
			template_page.close();
		}
	}
	
}
